package main

import (
	"fmt"
	"os"
	"time"

	"gitee.com/haifengat/goxele"
)

func main() {
	os.Chdir("../")

	t := goxele.NewTrade()
	for _, v := range []string{"ACCOUNT_ID", "ACCOUNT_PWD", "APP_ID", "AUTH_CODE", "TRADE_SERVER_IP", "TRADE_SERVER_PORT", "QUERY_SERVER_IP", "QUERY_SERVER_PORT"} {
		t.SetConfig(v, os.Getenv(v))
	}
	t.SetConfig("TCP_WORKER_BUSY_LOOP_ENABLED", "true")

	var lastID int32
	type Event int
	ch := make(chan Event)

	t.OnStart = func(errorCode int, isFirstTime bool) {
		fmt.Println("onstart: ", errorCode)
		t.Login()
	}
	t.OnLogin = func(errorCode, exchangeCount int) {
		fmt.Println("login: ", errorCode)
	}
	t.OnLoadFinished = func(account *goxele.XTFAccount) {
		// fmt.Println(account)
		lastID = account.LastLocalOrderID
		ch <- Event(1)
	}
	t.OnInstrument = func(event int, instrument *goxele.XTFInstrument) {
		fmt.Println("instrument: ", instrument)
	}
	t.OnExchange = func(event, action int, exchange *goxele.XTFExchange) {
		fmt.Println("exchange: ", exchange)
	}
	t.OnOrder = func(errorCode int, order *goxele.XTFOrder) {
		if order.IsHistory {
			return
		}
		if errorCode != 0 {
			fmt.Println("OnOrder error: ", errorCode)
		} else {
			fmt.Printf("%+v\n", *order)
		}
	}
	t.OnCancelOrder = func(errorCode int, cancelOrder *goxele.XTFOrder) {
		if cancelOrder.IsHistory {
			return
		}
		fmt.Println("OnCancelOrder", errorCode)
	}
	t.OnTrade = func(trade *goxele.XTFTrade) {
		if trade.IsHistory {
			return
		}
		fmt.Println(trade)
	}

	t.Start()
	select {
	case <-ch:
		fmt.Println("OnLoadFinished") // 登录完成
	case <-time.NewTimer(5 * time.Second).C:
		fmt.Println("timeout")
		return
	}
	fmt.Printf("%+v\n", t.Instruments)

	// res := t.FindOrders()
	// fmt.Println(res)
	fmt.Println("insert order ...")
	inst := t.GetInstrumentByID("ru2305")
	lastID += 1
	res := t.InsertOrder(inst, goxele.XTFInputOrder{
		LocalOrderID:         goxele.Uint32{}.FromUint32(uint32(lastID)),
		Direction:            goxele.XFT_D_Buy,
		OffsetFlag:           goxele.XTF_OF_Open,
		OrderType:            goxele.XTF_ODT_Limit,
		OrderFlag:            goxele.XTF_ODF_Normal,
		OrderPrice:           goxele.Float{}.FromFloat64(11680.0),
		OrderVolume:          goxele.Uint32{}.FromUint32(2),
		OrderMinVolume:       goxele.Uint32{}.FromUint32(1),
		ChannelSelectionType: goxele.XTF_CS_Auto,
		ChannelID:            0,
	})
	if res != 0 {
		fmt.Println("insertorder, error: ", res)
	}

	// defer t.Stop()
	select {}
}
